package com.pengpai.pangucms.controller;

import com.pengpai.pangucms.DTO.WebMessageDTO;
import com.pengpai.pangucms.entity.WebMessage;
import com.pengpai.pangucms.service.IWebMessageService;
import com.pengpai.pangucms.utils.R;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Objects;

@Slf4j
@Controller
@RequestMapping("/api")
public class ApiController {

    @Autowired
    private IWebMessageService webMessageService;

    @GetMapping("/category/{id}/{page}")
    public void categoryList(@PathVariable String id, @PathVariable String page, HttpServletResponse response) throws IOException {
        response.sendRedirect("http://localhost:8080/category/id/{id}/p/{page}");
        log.info("category:{},page:{},limit:{}",id,page);
    }

    @PostMapping("/webMessage")
    @ResponseBody
    public R uploadWebMessage (WebMessageDTO webMessageDTO, HttpSession httpSession){
        WebMessage webMessage = new WebMessage();
        webMessage.setPhone(webMessageDTO.getPhone());
        webMessage.setEmail(webMessageDTO.getEmail());
        webMessage.setName(webMessageDTO.getName());
        webMessage.setSubject(webMessageDTO.getSubject());
        webMessage.setMessage(webMessageDTO.getMessage());

        String code = (String) httpSession.getAttribute("captcha");
        String lowerCode = code.toLowerCase();
        if (!Objects.equals(lowerCode, webMessageDTO.getCaptcha().toLowerCase())){
            return R.fail(".......");
        }else {
            webMessage.setAskDate(LocalDateTime.now());
            webMessageService.save(webMessage);
            return R.success();
        }

    }
}
